<template>
  <div class="problems-page">
    <div class="container">
      <section class="header-section">
        <h1 class="page-title">题目检索</h1>
        <div class="search-bar">
          <input type="text" v-model="searchForm.keyword" placeholder="搜索题目..." class="search-input" @keyup.enter="searchProblems">
          <button class="search-btn" @click="searchProblems">搜索</button>
        </div>
        <div class="filter-container">
          <select class="filter-select" v-model="searchForm.type">
            <option value="">选择类型</option>
            <option value="1">1.单选题</option>
            <option value="2">2.多选题</option>
            <option value="3">3.判断题</option>
            <option value="4">4.选择填空题</option>
            <option value="5">5.编程填空题</option>
            <option value="6">6.修改编程题</option>
            <option value="7">7.编程题</option>
          </select>
          <select class="filter-select" v-model="searchForm.difficulty">
            <option value="">选择难度</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
          </select>
        </div>
      </section>

      <section class="problems-table">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>题目名称</th>
              <th>类型</th>
              <th>难度</th>
              <th>完成率</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading">
              <td colspan="6" style="text-align: center; padding: 40px; color: #666;">
                <div>🔄 正在加载题目数据...</div>
              </td>
            </tr>
            <tr v-else-if="problems.length === 0">
              <td colspan="6" style="text-align: center; padding: 40px; color: #666;">
                <div>📭 暂无题目数据</div>
              </td>
            </tr>
            <tr v-else v-for="problem in problems" :key="problem.id">
              <td>{{ problem.id }}</td>
              <td>
                <a @click.prevent="viewProblemDetail(problem.id)" class="problem-link" style="cursor: pointer;">{{ problem.title }}</a>
              </td>
              <td>
                <span class="type-tag">{{ problem.typeText }}</span>
              </td>
              <td>
                <span :class="['difficulty-tag', `level-${problem.difficulty}`]">{{ problem.difficultyText }}</span>
              </td>
              <td>{{ problem.completeRate }}</td>
              <td>
                <button class="action-btn" @click="viewProblemDetail(problem.id)">查看详情</button>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div class="pagination">
          <button class="pagination-btn" @click="goToPage(currentPage - 1)" :disabled="currentPage <= 1">&lt;</button>
          <button 
            v-for="page in visiblePages" 
            :key="page" 
            class="pagination-btn" 
            :class="{ active: page === currentPage }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <span v-if="totalPages > 5">...</span>
          <button class="pagination-btn" @click="goToPage(currentPage + 1)" :disabled="currentPage >= totalPages">&gt;</button>
        </div>
        
        <div class="page-jump">
          <span class="jump-label">跳转到</span>
          <input 
            type="number" 
            v-model="jumpPage" 
            @keyup.enter="jumpToPage"
            placeholder="页码" 
            class="jump-input"
            min="1"
            :max="totalPages"
          >
          <button class="jump-btn" @click="jumpToPage">跳转</button>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
import api from '@/api/config'
import { getTestQuestionList } from '@/api/testQuestion'
import logger from '../utils/logger.js'

export default {
  name: 'ProblemsView',
  data() {
    return {
      // 搜索表单数据
      searchForm: {
        keyword: '',
        type: '',
        difficulty: '',
        isPublic: '',
        label: ''
      },
      
      // 分页数据
      currentPage: 1,
      totalPages: 1,
      totalItems: 0,
      
      // 页码跳转输入
      jumpPage: '',
      
      // 加载状态
      loading: false,
      problems: [
        {
          id: 'P001',
          title: '两数之和',
          type: '7',
          typeText: '编程题',
          difficulty: '2',
          difficultyText: '2',
          completeRate: '78%'
        },
        {
          id: 'P002',
          title: '链表反转',
          type: '7',
          typeText: '编程题',
          difficulty: '3',
          difficultyText: '3',
          completeRate: '65%'
        },
        {
          id: 'P003',
          title: '二叉树遍历',
          type: '7',
          typeText: '编程题',
          difficulty: '3',
          difficultyText: '3',
          completeRate: '62%'
        },
        {
          id: 'P004',
          title: '动态规划问题',
          type: '7',
          typeText: '编程题',
          difficulty: '5',
          difficultyText: '5',
          completeRate: '45%'
        },
        {
          id: 'P005',
          title: '贪心算法示例',
          type: '5',
          typeText: '编程填空题',
          difficulty: '4',
          difficultyText: '4',
          completeRate: '58%'
        },
        {
          id: 'P006',
          title: '字符串匹配',
          type: '1',
          typeText: '单选题',
          difficulty: '2',
          difficultyText: '2',
          completeRate: '82%'
        },
        {
          id: 'P007',
          title: '回溯算法',
          type: '6',
          typeText: '修改编程题',
          difficulty: '6',
          difficultyText: '6',
          completeRate: '40%'
        },
        {
          id: 'P008',
          title: '图论基础',
          type: '2',
          typeText: '多选题',
          difficulty: '4',
          difficultyText: '4',
          completeRate: '56%'
        },
      ]
    }
  },
  
  computed: {
    // 计算可见的页码
    visiblePages() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      return pages
    }
  },
  
  mounted() {
    // 从 URL query 参数恢复状态（如果有的话）
    const query = this.$route.query
    let hasRestoredState = false
    
    if (query.page) {
      this.currentPage = parseInt(query.page) || 1
      hasRestoredState = true
      logger.log('🔄 从URL恢复页码:', this.currentPage)
    }
    if (query.keyword) {
      this.searchForm.keyword = query.keyword
      hasRestoredState = true
      logger.log('🔄 从URL恢复关键词:', query.keyword)
    }
    if (query.type) {
      this.searchForm.type = query.type
      hasRestoredState = true
      logger.log('🔄 从URL恢复类型:', query.type)
    }
    if (query.difficulty) {
      this.searchForm.difficulty = query.difficulty
      hasRestoredState = true
      logger.log('🔄 从URL恢复难度:', query.difficulty)
    }
    
    // 如果从URL恢复了状态，不要重置页码
    // 否则执行新搜索，重置到第1页
    logger.log('🔄 mounted: hasRestoredState =', hasRestoredState)
    this.searchProblems(!hasRestoredState)
  },
  
  methods: {
    // 搜索题目
    async searchProblems(resetPage = true) {
      // 防止重复请求
      if (this.loading) {
        logger.log('🔄 搜索正在进行中，跳过重复请求')
        return
      }
      
      // 如果是新搜索（不是翻页），重置到第1页
      if (resetPage) {
        this.currentPage = 1
      }
      
      this.loading = true
      const requestId = Date.now()
      logger.log(`🚀 开始搜索请求 #${requestId}`)
      
      try {
        logger.log('🔍 开始搜索题目...')
        logger.log('🔍 搜索参数:', this.searchForm)
        logger.log('🔍 当前页码:', this.currentPage)
        logger.log('🔍 当前页码类型:', typeof this.currentPage)
        logger.log('🔍 当前页码值检查:', {
          原始值: this.currentPage,
          是否为空: this.currentPage === null || this.currentPage === undefined,
          是否为字符串: typeof this.currentPage === 'string',
          字符串长度: typeof this.currentPage === 'string' ? this.currentPage.length : 'N/A'
        })
        
        // 构造请求参数，根据后端QuestionQueryDTO要求：
        // page必须有值，size不传递，其余5个参数可有可无值
        const params = {}
        
        // 处理page参数（必填）
        let pageValue = parseInt(this.currentPage, 10)
        if (isNaN(pageValue) || pageValue < 1) {
          logger.warn('⚠️ page参数无效，使用默认值1')
          pageValue = 1
          this.currentPage = 1
        }
        params.page = pageValue
        
        // 处理可选参数（只有有值时才添加）
        if (this.searchForm.keyword && this.searchForm.keyword.trim()) {
          params.keyword = this.searchForm.keyword.trim()
        }
        if (this.searchForm.type) {
          params.type = parseInt(this.searchForm.type, 10)
        }
        if (this.searchForm.difficulty) {
          params.difficulty = parseInt(this.searchForm.difficulty, 10)
        }
        if (this.searchForm.isPublic) {
          params.isPublic = parseInt(this.searchForm.isPublic, 10)
        }
        if (this.searchForm.label && this.searchForm.label.trim()) {
          params.label = this.searchForm.label.trim()
        }
        
        // 注意：不传递size参数，后端DTO中已经划掉了
        
        logger.log('🔍 最终请求参数:', params)
        logger.log('📋 参数详情:', {
          page: `${params.page} [必填]`,
          keyword: params.keyword || '未设置',
          type: params.type || '未设置', 
          difficulty: params.difficulty || '未设置',
          isPublic: params.isPublic || '未设置',
          label: params.label || '未设置'
        })
        
        // 构造完整的URL用于调试（显示最终的查询参数格式）
        const urlParams = new URLSearchParams()
        
        // 重要：按照与params对象相同的顺序添加参数
        const orderedKeys = Object.keys(params)
        logger.log('🔍 参数顺序:', orderedKeys)
        
        orderedKeys.forEach(key => {
          if (params[key] !== undefined && params[key] !== null) {
            urlParams.append(key, String(params[key]))  // 确保转为字符串
            logger.log(`🔗 添加URL参数 [${orderedKeys.indexOf(key) + 1}]: ${key} = ${params[key]} (${typeof params[key]})`)
          } else {
            logger.warn(`⚠️ 跳过无效参数: ${key} = ${params[key]}`)
          }
        })
        
        const queryString = urlParams.toString()
        const finalUrl = `/api/goc/testQuestion/list?${queryString}`
        
        logger.log('🌐 最终请求URL (Params形式):', finalUrl)
        logger.log('🔍 URL查询参数字符串:', queryString)
        logger.log('🔍 查询参数是否包含page:', queryString.includes('page='))
        logger.log('🔍 page参数在URL中的位置:', queryString.indexOf('page='))
        logger.log('🔍 URLSearchParams检查:', {
          参数数量: urlParams.size,
          所有参数: Array.from(urlParams.entries()),
          page参数值: urlParams.get('page'),
          page参数位置: Array.from(urlParams.entries()).findIndex(([k]) => k === 'page')
        })
        
        // 特别验证page参数是否在最后位置
        const entries = Array.from(urlParams.entries())
        const pageIndex = entries.findIndex(([key]) => key === 'page')
        const isPageLast = pageIndex === entries.length - 1
        logger.log('🎯 page参数位置验证:', {
          总参数数: entries.length,
          page参数索引: pageIndex,
          page是否在最后: isPageLast,
          实际参数顺序: entries.map(([k, v]) => `${k}=${v}`).join('&')
        })
        
        // 发送GET请求到后端 (axios会自动将params转为URL查询参数)
        logger.log('🚀 准备发送请求，使用以下参数传递方式:')
        logger.log('📋 Method 1 - axios params对象:', { params })
        logger.log('🔗 Method 2 - 完整URL:', finalUrl)
        
        // 专注于GET请求的两种方式
        logger.log('📋 只使用GET请求方式（后端确认）')
        
        // 使用专门的testQuestion API函数
        logger.log('🌐 [新方式] 使用testQuestion API...')
        logger.log('📋 发送的params对象:', JSON.stringify(params, null, 2))
        let response
        try {
          response = await getTestQuestionList(params)
          logger.log('✅ testQuestion API调用成功！')
        } catch (error) {
          logger.warn('⚠️ testQuestion API失败，尝试备选方案...')
          logger.error('错误详情:', error.response?.data || error.message)
          
          // 备选方案：直接使用原来的axios调用
          try {
            logger.log('🌐 [备选] 使用原始axios方式...')
            response = await api.get('/goc/testQuestion/list', { 
              params: params,
              timeout: 15000
            })
            logger.log('✅ 原始axios方式成功！')
          } catch (error2) {
            logger.error('❌ 两种API调用方式都失败了')
            logger.error('testQuestion API错误:', error.response?.data || error.message)
            logger.error('原始axios错误:', error2.response?.data || error2.message)
            
            // 提供详细的错误分析
            logger.log('🔍 错误分析:')
            logger.log('- testQuestion API状态码:', error.response?.status || '无响应')
            logger.log('- 原始axios状态码:', error2.response?.status || '无响应')
            logger.log('- 可能的解决方案:')
            logger.log('  1. 检查后端接口路径是否正确')
            logger.log('  2. 检查参数名称是否匹配后端期望')
            logger.log('  3. 检查参数类型是否正确')
            logger.log('  4. 检查网络连接和代理设置')
            
            throw error2
          }
        }
        
        logger.log('✅ 题目搜索成功:', response)
        logger.log('📊 后端返回的数据结构:', {
          hasData: !!response.data,
          dataKeys: response.data ? Object.keys(response.data) : [],
          recordsLength: response.data?.records?.length || 0,
          pages: response.data?.pages,
          total: response.data?.total
        })
        
        if (response && response.data) {
          // 处理后端返回的题目列表
          const problemList = response.data.records || response.data.list || response.data || []
          this.problems = this.formatProblems(problemList)
          
          // 处理分页信息
          this.totalPages = response.data.pages || response.data.totalPages || 1
          this.totalItems = response.data.total || response.data.totalElements || problemList.length
          
          logger.log('📋 处理后的数据:', {
            problemsCount: this.problems.length,
            totalPages: this.totalPages,
            totalItems: this.totalItems
          })
          
          // 更新 URL query 参数，保存当前状态
          this.updateURLQuery()
        
          logger.log(`✅ 搜索请求 #${requestId} 完成`)
        } else {
          this.problems = []
          this.totalPages = 1
          this.totalItems = 0
        }
        
      } catch (error) {
        logger.error('❌ 题目搜索失败:', error)
        
        // 详细的错误信息记录
        logger.error('📋 错误详细信息:', {
          message: error.message,
          status: error.response?.status,
          statusText: error.response?.statusText,
          url: error.config?.url,
          responseData: error.response?.data,
          isNetworkError: !error.response,
          timestamp: new Date().toISOString()
        })
        
        // 根据错误类型显示不同的提示信息
        let errorMessage = '搜索失败，请稍后重试'
        
        if (error.response?.status === 401) {
          errorMessage = '权限验证失败，请检查登录状态'
          logger.warn('⚠️ 题目搜索API返回401，但不会自动退出登录')
        } else if (error.response?.status === 403) {
          errorMessage = '权限不足，无法访问题目数据'
        } else if (error.response?.status === 404) {
          errorMessage = '题目数据接口不存在'
        } else if (error.response?.status === 500) {
          errorMessage = '服务器错误，请稍后重试'
        } else if (!error.response) {
          errorMessage = '网络连接失败，请检查网络设置'
        }
        
        this.$message?.error?.(errorMessage) || alert(errorMessage)
        
        // 失败时显示默认数据
        this.problems = this.getDefaultProblems()
        this.totalPages = 1
        this.totalItems = this.problems.length
        
        logger.log(`❌ 搜索请求 #${requestId} 失败`)
      } finally {
        this.loading = false
        logger.log(`🏁 搜索请求 #${requestId} 结束，loading状态已重置`)
      }
    },
    
    // 格式化后端返回的题目数据
    formatProblems(rawProblems) {
      logger.log('🔄 开始格式化题目数据，原始数据样本:', rawProblems[0])
      
      return rawProblems.map((problem, index) => {
        const formatted = {
          id: problem.id || problem.testQuestionId || problem.questionId || `Q${index + 1}`,
          title: problem.questionName || problem.title || problem.questionTitle || problem.name || '未知题目',
          type: problem.questionType || problem.type || '',
          typeText: this.getTypeText(problem.questionType || problem.type),
          difficulty: problem.difficulty || problem.difficultyLevel || '',
          difficultyText: String(problem.difficulty || problem.difficultyLevel || ''),
          completeRate: problem.completeRate || problem.completionRate || '0%'
        }
        
        if (index === 0) {
          logger.log('📝 格式化后的数据样本:', formatted)
        }
        
        return formatted
      })
    },
    
    // 获取题目类型文本
    getTypeText(type) {
      const typeMap = {
        '1': '单选题',
        '2': '多选题', 
        '3': '判断题',
        '4': '选择填空题',
        '5': '编程填空题',
        '6': '修改编程题',
        '7': '编程题'
      }
      return typeMap[type] || '未知类型'
    },
    
    // 跳转到指定页码
    goToPage(page) {
      const targetPage = Number(page)  // 确保页码为数字
      
      if (targetPage < 1 || targetPage > this.totalPages || targetPage === this.currentPage) {
        return
      }
      
      logger.log('📄 跳转页码:', `${this.currentPage} -> ${targetPage}`)
      this.currentPage = targetPage
      this.searchProblems(false)  // 翻页时不重置页码
    },
    
    // 跳转到输入的页码
    jumpToPage() {
      const targetPage = parseInt(this.jumpPage, 10)
      
      if (isNaN(targetPage)) {
        this.$message?.warning?.('请输入有效的页码') || alert('请输入有效的页码')
        return
      }
      
      if (targetPage < 1 || targetPage > this.totalPages) {
        this.$message?.warning?.(`页码范围：1-${this.totalPages}`) || alert(`页码范围：1-${this.totalPages}`)
        return
      }
      
      logger.log('🎯 跳转到指定页码:', targetPage)
      this.currentPage = targetPage
      this.jumpPage = ''  // 清空输入框
      this.searchProblems(false)  // 跳转页码时不重置
    },
    
    // 更新 URL query 参数
    updateURLQuery() {
      const query = {
        page: this.currentPage,
        keyword: this.searchForm.keyword || undefined,
        type: this.searchForm.type || undefined,
        difficulty: this.searchForm.difficulty || undefined
      }
      
      // 移除值为 undefined 的属性
      Object.keys(query).forEach(key => {
        if (query[key] === undefined) {
          delete query[key]
        }
      })
      
      // 使用 replace 而不是 push，避免在历史记录中创建太多条目
      this.$router.replace({ 
        path: this.$route.path, 
        query: query 
      }).catch(err => {
        // 忽略导航重复错误
        if (err.name !== 'NavigationDuplicated') {
          console.error(err)
        }
      })
    },
    
    // 查看题目详情
    viewProblemDetail(problemId) {
      logger.log('🔍 查看题目详情，ID:', problemId)
      
      // 确保当前状态已保存到 URL（通常已经在 searchProblems 中保存了）
      this.updateURLQuery()
      
      // 跳转到详情页
      this.$router.push(`/problem/${problemId}`)
    },
    
    // 获取默认题目数据（作为fallback）
    getDefaultProblems() {
      return [
        {
          id: 'P001',
          title: '两数之和',
          type: '7',
          typeText: '编程题',
          difficulty: '2',
          difficultyText: '2',
          completeRate: '78%'
        },
        {
          id: 'P002',
          title: '链表反转',
          type: '7',
          typeText: '编程题',
          difficulty: '3',
          difficultyText: '3',
          completeRate: '65%'
        },
        {
          id: 'P003',
          title: '二叉树遍历',
          type: '7',
          typeText: '编程题',
          difficulty: '3',
          difficultyText: '3',
          completeRate: '62%'
        },
        {
          id: 'P004',
          title: '动态规划问题',
          type: '7',
          typeText: '编程题',
          difficulty: '5',
          difficultyText: '5',
          completeRate: '45%'
        },
        {
          id: 'P005',
          title: '贪心算法示例',
          type: '5',
          typeText: '编程填空题',
          difficulty: '4',
          difficultyText: '4',
          completeRate: '58%'
        },
        {
          id: 'P006',
          title: '字符串匹配',
          type: '1',
          typeText: '单选题',
          difficulty: '2',
          difficultyText: '2',
          completeRate: '82%'
        },
        {
          id: 'P007',
          title: '回溯算法',
          type: '6',
          typeText: '修改编程题',
          difficulty: '6',
          difficultyText: '6',
          completeRate: '40%'
        },
        {
          id: 'P008',
          title: '图论基础',
          type: '2',
          typeText: '多选题',
          difficulty: '4',
          difficultyText: '4',
          completeRate: '56%'
        }
      ]
    }
  }
}
</script>

<style scoped>
.problems-page {
  padding: 40px 0;
  min-height: calc(100vh - 300px); /* 减去头部和页脚的高度 */
  background-color: #f7f9fc;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-section {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
}

.search-btn {
  background-color: #3e8ef7;
  color: white;
  border: none;
  padding: 0 20px;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 120px;
}

.problems-table {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f9f9f9;
  color: #555;
  font-weight: 600;
}

.problem-link {
  color: #3e8ef7;
  text-decoration: none;
  font-weight: 500;
}

.problem-link:hover {
  text-decoration: underline;
}

.type-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #1890ff;
  color: white;
}

.difficulty-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

/* 难度等级1-2：简单（绿色） */
.difficulty-tag.level-1,
.difficulty-tag.level-2 {
  background-color: #52c41a;
}

/* 难度等级3-4：中等（橙色） */
.difficulty-tag.level-3,
.difficulty-tag.level-4 {
  background-color: #fa8c16;
}

/* 难度等级5-6：困难（红色） */
.difficulty-tag.level-5,
.difficulty-tag.level-6 {
  background-color: #f5222d;
}

.action-btn {
  background-color: #3e8ef7;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  gap: 5px;
}

.pagination-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination-btn.active {
  background-color: #3e8ef7;
  color: white;
  border-color: #3e8ef7;
}

.pagination-btn:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
  border-color: #e0e0e0;
}

.page-jump {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px 0;
  gap: 10px;
}

.jump-label {
  color: #666;
  font-size: 14px;
}

.jump-input {
  width: 80px;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.jump-input:focus {
  outline: none;
  border-color: #3e8ef7;
}

/* 移除数字输入框的上下箭头 */
.jump-input::-webkit-outer-spin-button,
.jump-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.jump-input[type=number] {
  -moz-appearance: textfield;
}

.jump-btn {
  background-color: #3e8ef7;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.jump-btn:hover {
  background-color: #2d7ae8;
}
</style> 